package com.cykj.pos.controller.task;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.cykj.common.core.domain.AjaxResult;
import com.cykj.common.core.domain.entity.SysDept;
import com.cykj.common.core.domain.entity.SysUser;
import com.cykj.pos.controller.TestDTO.HttpClientHandler;
import com.cykj.pos.domain.BizFeesCharged;
import com.cykj.pos.domain.BizMerchant;
import com.cykj.pos.domain.BizPosMachine;
import com.cykj.pos.domain.SynchronizationDataDTO;
import com.cykj.pos.domain.dto.BizAgentidAppkeyDTO;
import com.cykj.pos.mapper.BizMerchantMapper;
import com.cykj.pos.mapper.BizMerchantReceiverMapper;
import com.cykj.pos.service.IBizFeesChargedService;
import com.cykj.pos.service.IBizPosMachineService;
import com.cykj.pos.service.IBizTransactionAmount;
import com.cykj.pos.util.PosOneUtil;
import com.cykj.system.mapper.SysDeptMapper;
import com.cykj.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
@RestController
@RequestMapping("/test")
public class TaskFeesCharged {

    @Resource
    private IBizFeesChargedService bizFeesChargedService;
    @Resource
    private IBizTransactionAmount bizTransactionAmount;
    @Resource
    private IBizPosMachineService bizPosMachineService;
    @Resource
    private BizMerchantMapper bizMerchantMapper;
    @Resource
    private BizMerchantReceiverMapper bizMerchantReceiverMapper;
    @Value("${cykj.path}")
    private String path;

    //费用查询  发钱
    @PostMapping("/selectFeesCharged")
    @Transactional
//    @Scheduled(cron = "0 0 3 * * ?")
    public AjaxResult selectFeesCharged() throws Exception {
        Properties properties = this.getMyProperty();
        if(!"2".equals(properties.getProperty("type"))){
            return AjaxResult.success();
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //查询费用收取列表的费用id
        System.out.println("-----------------------------");
        System.out.println("执行定时任务流量费查询" + new Date());
        System.out.println("-----------------------------");
        //查询未发放的流量费
        List<BizFeesCharged> list = bizFeesChargedService.selectBizFeeCharged();
        for (BizFeesCharged bizFeesCharged : list) {
            BizFeesCharged bizFeesCharged1 = new BizFeesCharged();
//            System.out.println("流量费用收取了 分钱 改状态");
//            bizFeesCharged1.setMamountId(bizFeesCharged.getMamountId());
//            bizFeesChargedService.saveOrUpdate(bizFeesCharged1);
            SynchronizationDataDTO sy = new SynchronizationDataDTO();
            sy.setSim_amt(Integer.parseInt(bizFeesCharged.getSimcardfee()));
            sy.setPos_sn(bizFeesCharged.getSn());
            sy.setHost_date(sdf.format(new Date()));
            sy.setMerchant_no(bizFeesCharged.getMerchantNo());
            sy.setUuid(bizFeesCharged.getUuid());
            bizTransactionAmount.returnSimAmt(sy,true);
            System.out.println("流量费分钱了 uuid" + bizFeesCharged.getUuid());
        }
        return AjaxResult.success();
    }
    @Transactional
    @PostMapping("/bcllf")
    public AjaxResult bcllf(String posCodes) throws Exception {

        String [] posCode =posCodes.split(",");
        for (String sn:posCode){
            BizPosMachine bizPosMachine=new BizPosMachine();
            bizPosMachine.setPosCode(sn);
            bizPosMachine=bizPosMachineService.selectPosBySnCode(bizPosMachine.getPosCode());
            BizMerchant bizMerchant= bizMerchantMapper.selectById(bizPosMachine.getMerchId());
            SysDept dept=bizMerchantMapper.getDeptByUserId(bizMerchant.getUserId());
            List<JSONObject> list=this.getFeesCharged(bizPosMachine,bizMerchant);
            for (JSONObject jsonObject:list){
                this.saveBizFeesCharged(jsonObject,dept,null);
            }
        }
        return AjaxResult.success("成功");
    }
    //费用收取列表
    @Transactional
//    @Scheduled(cron = "0 0 1 * * ?")
//    @PostMapping("/timerGetChargeList")
    public AjaxResult timerGetChargeList() throws Exception {
        Properties properties = this.getMyProperty();
        if(!"2".equals(properties.getProperty("type"))){
            return AjaxResult.success();
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:dd");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        Date end = c.getTime();
        String dqrq = format.format(end);//当前日期
        c.add(Calendar.DATE, -1);
        Date start = c.getTime();
        String beforeDay = format.format(start);//前一天
        //查询所有的设备
        Date begindate=new Date();
        System.out.println("------------------------------");
        System.out.println("-----------定时任务查询费用收取列表开始-------------------" + begindate);
        System.out.println("------------------------------");
        List<BizPosMachine> bizPosMachineList = bizPosMachineService.timerGetAllPos();
        for (BizPosMachine bizPosMachine : bizPosMachineList) {
            bizPosMachine=bizPosMachineService.selectPosBySnCode(bizPosMachine.getPosCode());
            BizMerchant bizMerchant= bizMerchantMapper.selectById(bizPosMachine.getMerchId());
            SysDept dept=bizMerchantMapper.getDeptByUserId(bizMerchant.getUserId());
            List<JSONObject> list=this.getFeesCharged(bizPosMachine,bizMerchant);
            for (JSONObject jsonObject:list){
                this.saveBizFeesCharged(jsonObject,dept,beforeDay);
            }
        }
        Date endDate=new Date();
        System.out.println("------------------------------");
        System.out.println("-----------定时任务查询费用收取列表结束-------------------" + endDate);
        System.out.println("-----------共计用时：-------------------" + (begindate.getTime()-endDate.getTime()));
        System.out.println("------------------------------");
        return AjaxResult.success("");
    }

    //请求接口获取收取流量费成功信息
    private List<JSONObject>  getFeesCharged(BizPosMachine bizPosMachine, BizMerchant bizMerchant) throws Exception {
        Long deptId= bizMerchantReceiverMapper.selectSysDeptId(bizMerchant.getUserId());
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverMapper.selectAgentidAppkey(bizMerchant.getUserId(),deptId);//获取机构配置文件
        String secretAgentid=bizAgentidAppkeyDTO.getAgentid();//机构编码
        //循环查询费用收取列表
        String snCode = bizPosMachine.getPosCode();
        Map<String, String> data2 = new HashMap<String, String>();
        String url2 = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=teramtDao&Methods=list";
        //  data2.put("creatdate", beforeDay);
        data2.put("sn", snCode);
        data2.put("mersource", "OUTMER");
        data2.put("agentid", secretAgentid);
        data2.put("key", bizAgentidAppkeyDTO.getKey());
        data2.put("sign", PosOneUtil.generateSignature(data2));
        System.out.println("----------" + PosOneUtil.generateSignature(data2));
        System.out.println("---------" + data2);
        String result2 = HttpClientHandler.noPictureRequest(url2, data2);
        System.out.println("返回:" + result2);
        return this.jx(result2);
    }

    //解析返回
    private List<JSONObject> jx( String result2 ){
        JSONObject jsonObject2 = JSONObject.parseObject(result2);
        String retCode2 = jsonObject2.getString("ret_code");
        List<JSONObject> listObject=new ArrayList<JSONObject>();
        if (retCode2.equals("0")) { //判断是否获取成功
            JSONObject data4 = jsonObject2.getJSONObject("data");
            Integer totcount = data4.getInteger("totcount");
            if (totcount > 0) { //判断是否查询到条数
                JSONArray list = data4.getJSONArray("list");
                if (list.size() > 0) {  // 判断查寻到的list是否有值
                    for (int i = 0; i < list.size(); i++) {
                        JSONObject jsonObject1 = list.getJSONObject(i);
                        String mamount_id = jsonObject1.getString("mamount_id"); //费用ID(隐藏)
                        String orgnname = jsonObject1.getString("orgnname");   //所属代理
                        String merchant_no = jsonObject1.getString("merchant_no");  //系统商户编号
                        String sn = jsonObject1.getString("sn");  //SN
                        String simcardfee = jsonObject1.getString("simcardfee");  //收取费用
                        String mamount_starts = jsonObject1.getString("mamount_starts");  //状态(0-初始 1-成功 2-取消 3-待收取 9-未知)
                        String amt_type = jsonObject1.getString("amt_type");  //费用类型（0-流量费 1-设备款）
                        String creatdate = jsonObject1.getString("creatdate");  //创建日期
                        String host_date = jsonObject1.getString("host_date");  //收取日期
                        //查询成功 查询的信息存到 费用收取列表
                        // if (!mamount_starts.equals("1") && !mamount_starts.equals("2") && amt_type.equals("0")) {
                        if (mamount_starts.equals("1") && amt_type.equals("0")) {    //查询成功的并且是流量费
                            listObject.add(jsonObject1);
                        }
                    }
                } else {
                    System.out.println("没有list");
                }
            }
        }
        return listObject;
    }

    //存储流量费信息
    private void saveBizFeesCharged(JSONObject jsonObject1,SysDept dept,String beforeDay){ //查询成功的并且是流量费
        String host_date = jsonObject1.getString("host_date");  //收取日期
        String mamount_id = jsonObject1.getString("mamount_id"); //费用ID(隐藏)
        String merchant_no = jsonObject1.getString("merchant_no");  //系统商户编号
        String sn = jsonObject1.getString("sn");  //SN
        String simcardfee = jsonObject1.getString("simcardfee");  //收取费用
        String mamount_starts = jsonObject1.getString("mamount_starts");  //状态(0-初始 1-成功 2-取消 3-待收取 9-未知)
        String amt_type = jsonObject1.getString("amt_type");  //费用类型（0-流量费 1-设备款）
        String creatdate = jsonObject1.getString("creatdate");  //创建日期
        if(StringUtils.isBlank(beforeDay)||host_date.equals(beforeDay)){
            BizFeesCharged bizFeesCharged = new BizFeesCharged();
            bizFeesCharged.setMamountId(mamount_id);
            bizFeesCharged.setOrgnname(dept.getDeptName());
            bizFeesCharged.setMerchantNo(merchant_no);
            bizFeesCharged.setSn(sn);
            bizFeesCharged.setSimcardfee(simcardfee);
            bizFeesCharged.setMamountStarts(mamount_starts);
            bizFeesCharged.setAmtType(amt_type);
            bizFeesCharged.setCreatdate(creatdate);
            bizFeesCharged.setHostDate(host_date);
            bizFeesCharged.setUuid(IdWorker.getIdStr());
            bizFeesCharged.setRmbStatus("1"); //未发放
            BizFeesCharged byId = bizFeesChargedService.getById(mamount_id);
            if (byId == null) {
                System.out.println(mamount_id);
                bizFeesChargedService.insertBizFeesCharged(bizFeesCharged);
            }
        }
    }
    /**
     * @author: haoran
     * @date: 2022/8/18
     * 方法名称： 读取配置文件，是否启动定时器内的方法
     */
    public Properties getMyProperty() throws IOException {
//        InputStream in = new BufferedInputStream(new FileInputStream("/var/cms.properties"));
        InputStream in = new BufferedInputStream(new FileInputStream(path+"/cms.properties"));
        Properties p = new Properties();
        p.load(in);
        return p;
    }
   /* @RequestMapping("aaa")
    public AjaxResult aaa() {

        BizFeesCharged bizFeesCharged1 = new BizFeesCharged();
        bizFeesCharged1.setMamountStarts("1");
        bizFeesCharged1.setMamountId("11241");
        bizFeesChargedService.saveOrUpdate(bizFeesCharged1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SynchronizationDataDTO sy = new SynchronizationDataDTO();
        sy.setSim_amt("36");
        sy.setPos_sn("G20043A6308");
        sy.setHost_date(sdf.format(new Date()));
        sy.setUuid("1522402240885641218");
        bizTransactionAmount.returnSimAmt(sy);
        return AjaxResult.success();
    }

    @PostMapping("/testaaa")
    public AjaxResult testaaa() throws Exception {
        AjaxResult ajaxResult = AjaxResult.success();
        String sn = "G2004R07970";
        bizFeesChargedService.timerGetChargeList(sn);
        return ajaxResult;
    }*/

   /* public static void main(String[] args) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        Date end = c.getTime();
        String dqrq = format.format(end);//当前日期

        c.add(Calendar.DATE, -1);
        Date start = c.getTime();
        String qyt = format.format(start);//前一天
        System.out.println(qyt);
    }*/

}
